package com.tgy.JUC.CollectionUnSafe;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;

/***
 * @ClassName: ArrayUnsafe
 * @Description: ArrarList不安全测试 ,可以用Vector解决但是不推荐
 * @Auther: 送你一块二向箔
 * @Date: 11:23 2022/3/11
 * @version : V1.0
 */
public class ArrayUnsafe {
    public static void main(String[] args) {
/*        List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
        integers.forEach(System.out::println);*/
        //safeCollections();
        //unsafe();
        safeCopyOnWriteArrayList();

    }

    public static void safeCopyOnWriteArrayList(){
        List<String> strings = new CopyOnWriteArrayList<>();
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                strings.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(strings);
            }).start();
        }
        try {
            TimeUnit.SECONDS.sleep(3L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("==================");
        strings.forEach(System.out::println);
        System.out.println("==================");
    }



    public static void safeCollections(){
        List<String> strings = Collections.synchronizedList(new ArrayList<>());
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                strings.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(strings);
            }).start();
        }
        try {
            TimeUnit.SECONDS.sleep(3L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("==================");
        strings.forEach(System.out::println);
        System.out.println("==================");
    }



    public static void safeVector(){
        List<String> strings = new Vector<>();
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                strings.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(strings);
            }).start();
        }
        try {
            TimeUnit.SECONDS.sleep(3L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("==================");
        strings.forEach(System.out::println);
        System.out.println("==================");
    }

    public static void unsafe(){
        List<String> strings = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                strings.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(strings);
            }).start();
        }
        strings.forEach(System.out::println);
    }
}
